package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.*;
import android.view.animation.AnimationUtils;
import android.widget.*;
import com.lzx.iteam.adapter.ApprovalDataAdapter;
import com.lzx.iteam.bean.ApprovalData;
import com.lzx.iteam.widget.flowlayout.FlowLayout;
import com.lzx.iteam.widget.flowlayout.TagAdapter;
import com.lzx.iteam.widget.flowlayout.TagFlowLayout;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetApprovalMsg;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.*;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 04月 08日
 * Time: 下午3:20
 *
 * @QQ : 1234567890
 * **********************************
 */
public class ApprovalFragment extends Fragment implements AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener,View.OnClickListener,View.OnTouchListener{

    private ListView mListView;
    private ArrayList<ApprovalData> mListData = new ArrayList<ApprovalData>();;
    private ApprovalDataAdapter mAdapter;
    private Activity mActivity;
    private RelativeLayout mLayoutTitle;
    private LinearLayout mLayoutNull;
    private LinearLayout mLayoutBack;
    private LinearLayout mLayoutScreen;
    private Dialog mWaitDialog;
    private View mainView;

    private int mPosition = -1;
    private String mGroupId;       // 小组Id
    private int mListType;         // 审批类型 1：我的申请  2：待我审批 3：审批记录
    private String mUid;
    private int type,year,month;                    // 临时数据： 类型  年份  月份
    private int mTypeIndex,mYearIndex,mMonthIndex;  // 筛选字段： 类型  年份  月份
    private String[] mTypes = {"全部","  出差申请  ","  请假申请  ","  外出申请  ","  签到申请  "};
    private String[] mYears = new String[3];
    private String[] mMonths = {"全部","一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};
    private StringBuffer sb = new StringBuffer();
    private ArrayList<String> args = new ArrayList<String>();


    private CloudDBOperation mCloudDBOperation;
    private PopupWindow mScreenPop;
    private TagAdapter<String> adapter1;
    private TagAdapter<String> adapter2;
    private TagAdapter<String> adapter3;

    public static final int APPROVAL_DATA = 10001;
    public static final int APPROVAL_DELETE = 10002;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case APPROVAL_DATA:
                    if (msg.arg1 == 0){
                        mListData = (ArrayList<ApprovalData>) msg.obj;
                        if (mListData.size() == 0){
                            mLayoutNull.setVisibility(View.VISIBLE);
                            mListView.setVisibility(View.GONE);
                        }else{
                            mLayoutNull.setVisibility(View.GONE);
                            mListView.setVisibility(View.VISIBLE);
                        }
                        if (mListType == 2){
                            ((ApprovalActivity)mActivity).setNewMsg(mListData.size());
                        }
                        mAdapter.bindData(mListData);
                    }else{
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case APPROVAL_DELETE:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0){
                        Toast.makeText(mActivity,"删除成功",Toast.LENGTH_SHORT).show();
                        mCloudDBOperation.deleteOneApproval(mUid, mListType, mGroupId, mListData.get(mPosition).getApproval_id());
                        mListData.remove(mPosition);
                        mAdapter.notifyDataSetChanged();
                    }else{
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };


    public static ApprovalFragment newInstance(String groupId, int listType) {

        ApprovalFragment fragment = new ApprovalFragment();
        Bundle data = new Bundle();
        data.putString("group_id",groupId);
        data.putInt("list_type", listType);
        fragment.setArguments(data);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
        mGroupId = getArguments().getString("group_id");
        mListType = getArguments().getInt("list_type");
        mUid = PreferenceUtil.getInstance(mActivity).getString(PreferenceUtil.CLIENT_USEID, "－1");
        mCloudDBOperation = new CloudDBOperation(mActivity);
        Log.d("approval_fragment","   onCreate  " );
        int year = DateUtil.getYear(System.currentTimeMillis());
        mYears[0] = "全部";
        mYears[1] = (year - 1) + "";
        mYears[2] = year + "";
    }

    @Override
    public void onResume() {
        super.onResume();
        getApprovalData();

    }

    private void getApprovalData(){

        mListData = mCloudDBOperation.findApprovalData(mUid,mListType,mGroupId,sb.toString(),args);
        if (mListData.size() == 0){
            mLayoutNull.setVisibility(View.VISIBLE);
            mListView.setVisibility(View.GONE);
        }else{
            mLayoutNull.setVisibility(View.GONE);
            mListView.setVisibility(View.VISIBLE);
        }
        if (mListType == 2){
            ((ApprovalActivity)mActivity).setNewMsg(mListData.size());
        }
        mAdapter.bindData(mListData);
        Log.d("approval_fragment","onResume   size == " + mListData.size());
        if (mListType != 3){
            getCloudApprovalData();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.app_fg_layout,container,false);
        mLayoutTitle = (RelativeLayout) view.findViewById(R.id.rl_title_bar);
        mListView = (ListView) view.findViewById(R.id.ap_fg_item_iv);
        if (mListType == 3){
            mLayoutTitle.setVisibility(View.VISIBLE);
            // TODO 已经处理的审批页面 要去除下边距
            LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) mListView.getLayoutParams();
            linearParams.bottomMargin = 1;
            mListView.setLayoutParams(linearParams);
        }
        mLayoutBack = (LinearLayout) view.findViewById(R.id.approval_complete_ll_back);
        mLayoutBack.setOnClickListener(this);

        mLayoutNull = (LinearLayout) view.findViewById(R.id.ap_complete_null);
        mLayoutScreen = (LinearLayout) view.findViewById(R.id.approval_ll_screen);
        mLayoutScreen.setOnClickListener(this);

        mAdapter = new ApprovalDataAdapter(getActivity(),mListType);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);
        Log.d("approval_fragment","   onCreateView  " );
        if (mListType == 3){
            getCloudApprovalData();
        }
        view.setOnTouchListener(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

        final LayoutInflater mInflater = LayoutInflater.from(mActivity);
        mainView = mInflater.inflate(R.layout.ap_screen_pop_layout, null);
        final TagFlowLayout mFlType = (TagFlowLayout) mainView.findViewById(R.id.ap_screen_fl_type);
        final TagFlowLayout mFlYear = (TagFlowLayout) mainView.findViewById(R.id.ap_screen_fl_year);
        final TagFlowLayout mFlMonth = (TagFlowLayout) mainView.findViewById(R.id.ap_screen_fl_month);
        TextView mTvConfirm = (TextView) mainView.findViewById(R.id.ap_screen_confirm);
        TextView mTvBack = (TextView) mainView.findViewById(R.id.ap_screen_back);

        /**
         * 选择类型
         */
        mFlType.setAdapter(adapter1 = new TagAdapter<String>(mTypes)
        {

            @Override
            public View getView(FlowLayout parent, int position, String s)
            {
                TextView tv = (TextView) mInflater.inflate(R.layout.screen_tv_layout,
                        mFlType, false);
                tv.setText(s);
                return tv;
            }
        });
        adapter1.setSelected(0);
        mFlType.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
        {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent)
            {
                type = position;
                return false;
            }
        });

        /**
         * 选择年份
         */
        mFlYear.setAdapter(adapter2 = new TagAdapter<String>(mYears)
        {

            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.screen_tv_layout,
                        mFlYear, false);
                tv.setText(s);
                return tv;
            }
        });
        adapter2.setSelected(0);
        mFlYear.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
        {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent)
            {
                year = position;
                return false;
            }
        });

        /**
         * 选择月份
         */
        mFlMonth.setAdapter(adapter3 = new TagAdapter<String>(mMonths)
        {

            @Override
            public View getView(FlowLayout parent, int position, String s)
            {
                TextView tv = (TextView) mInflater.inflate(R.layout.screen_tv_month_layout,
                        mFlMonth, false);
                tv.setText(s);
                return tv;
            }
        });
        adapter3.setSelected(0);
        mFlMonth.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
        {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent)
            {
                month = position;
                return false;
            }
        });

        mTvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTypeIndex = type;
                mYearIndex = year;
                mMonthIndex = month;
                upDateScreenResult();
                mScreenPop.dismiss();

            }
        });

        mTvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter1.setSelected(0);
                adapter2.setSelected(0);
                adapter3.setSelected(0);
                type = 0;
                year = 0;
                month = 0;
            }
        });

    }


    private void upDateScreenResult(){
        sb.setLength(0);
        args.clear();

        if (mTypeIndex != 0){
            sb.append("and approval_type = ? ");
            args.add(mTypeIndex + "");
        }
        if (mYearIndex != 0){
            sb.append("and approval_year = ? ");
            args.add(mYears[mYearIndex]);
        }
        if (mMonthIndex != 0){
            sb.append("and approval_month = ? ");
            args.add(mMonthIndex + "");
        }

        mListData.clear();
        mListData = mCloudDBOperation.findApprovalData(mUid,mListType,mGroupId,sb.toString(),args);
        if (mListData.size() == 0){
            mLayoutNull.setVisibility(View.VISIBLE);
            mListView.setVisibility(View.GONE);
        }else{
            mLayoutNull.setVisibility(View.GONE);
            mListView.setVisibility(View.VISIBLE);
        }
        mAdapter.bindData(mListData);

    }



    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(mActivity,ApprovalDetailActivity.class);
        intent.putExtra("approvalData",mListData.get(position));
        intent.putExtra("list_type",mListType);
        intent.setAction("approval");
        startActivity(intent);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        mPosition = position;
        ApprovalData approvalData = mListData.get(position);
        if (mListType == 2 && approvalData.getApproval_status() == 0){

        }else if (mListType == 1 && approvalData.getApproval_status() == 0){
            showDeleteTalkDlg(approvalData.getApproval_id(),getString(R.string.ap_list_type_2));
        }else{
            showDeleteTalkDlg(approvalData.getApproval_id(),getString(R.string.ap_list_type_1));
        }
        return true;
    }

    public void showDeleteTalkDlg(final String appId,String message) {
        String okText = "确定";
        String cancelText = this.getString(R.string.cancel);
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(mActivity);
        mDialogUtil.titleDeleteMsgStyle("提示",okText, cancelText, message);
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                httpReqDlgShow();
                deleteApprovalData(appId);
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = AllDialogUtil.getInstance(mActivity).waitDialog();
            mWaitDialog.show();
        }

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    /**
     * 获取审批列表
     */
    private void getCloudApprovalData(){

        if (!StringUtil.isEmpty(mGroupId)){
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                    .getInstance().mSid));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
            nvps.add(new BasicNameValuePair("list_type", mListType + ""));
            GetApprovalMsg msg = new GetApprovalMsg(mHandler.obtainMessage(APPROVAL_DATA),mGroupId,mListType,mUid,mActivity);
            msg.mApi = AsynHttpClient.API_EVENT_APPROVAL_LIST;
            msg.mParams = nvps;
            AsynHttpClient.getInstance(mActivity).execEventHttp(msg);
        }else{
            mLayoutNull.setVisibility(View.VISIBLE);
            mListView.setVisibility(View.GONE);
        }

    }

    /**
     * 删除审批
     */
    private void deleteApprovalData(String appId){

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROCAL_ID, appId));
        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(APPROVAL_DELETE));
        msg.mApi = AsynHttpClient.API_EVENT_APPROVAL_DEL;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(mActivity).execEventHttp(msg);

    }

    public void update(String groupId){
        mGroupId = groupId;
        getApprovalData();
    }

    private void showScreenPop(){

        adapter1.setSelected(mTypeIndex);
        adapter2.setSelected(mYearIndex);
        adapter3.setSelected(mMonthIndex);

        mScreenPop = new PopupWindow(mActivity);
        mScreenPop.setBackgroundDrawable(new BitmapDrawable());
        mScreenPop.setFocusable(true);
        mScreenPop.setTouchable(true);
        mScreenPop.setOutsideTouchable(true);
        mScreenPop.setContentView(mainView);
        mScreenPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mScreenPop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mScreenPop.showAtLocation(mainView, Gravity.CENTER, 0, 0);
        mScreenPop.update();
        mainView.startAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.alpha_in));
        mainView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mScreenPop.dismiss();
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.approval_complete_ll_back:
                ((ApprovalActivity)mActivity).removeFragment();
                break;
            case R.id.approval_ll_screen:
                showScreenPop();
                break;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO  解决fragment点击能穿透问题
        return true;
    }
}
